<?php

namespace App\Http\Controllers\Setting;

use App\Http\Controllers\Controller;
use App\Models\Common\ApiResponse;
use App\Models\ParkingLot\Lane;
use App\Models\ParkingLot\ParkingLot;
use App\Models\ParkingLot\ParkingLotArea;
use App\Models\Setting\Setting;
use Illuminate\Http\Request;

class SettingController extends Controller
{
    public $name = '系统配置';

    public function info(Request $request): array
    {
        $data = $request->post();

        $result = [];
        if ($category = \Arr::get($data, 'category')) {
            $query = Setting::where('category', $category);

            if ($parkingLotID = \Arr::get($data, 'parking_lot_id')) {
                $query->where('parking_lot_id', $parkingLotID);
            }

            if ($key = \Arr::get($data, 'key')) {
                $setting = $query->where('key', $key)->first();

                ApiResponse::return('', $setting->value);
            }

            $settings = $query->get();
            foreach ($settings as $setting) {
                $result[$setting['key']] = $setting['value'];
            }
        }

        return ApiResponse::return('', $result);
    }

    public function store(Request $request): array
    {
        $admin = admin();

        $title = '';
        if ($category = $request->post('category')) {
            switch ($category) {
                case Setting::CATEGORY_SITE:
                    $title = '站点';
                    break;
                case Setting::CATEGORY_WECHAT:
                    $title = '公众号';
                    break;
                case Setting::CATEGORY_WMP_APP:
                    $title = '小程序-车主端';
                    break;
                case Setting::CATEGORY_WMP_ADMIN:
                    $title = '小程序-管理端';
                    break;
                case Setting::CATEGORY_WMP_MERCHANT:
                    $title = '小程序-商户端';
                    break;
            }
            $data = $request->post('data');
            if ($parkingLotID = $request->post('parking_lot_id') ?: '') {
                if (!ParkingLot::find($parkingLotID)) {
                    ApiResponse::return('未查询到车场信息', '', ApiResponse::CODE_INVALID_ARGUMENT);
                }
            }

            // 保存data的格式需要注意
            //  例如更新 wechat_appid 字段， $data = [ 'wechat_appid' => '12' ]
            // key 就是 data 的 key , value 对应的就是 data 的 value
            collect($data)->each(function ($item, $key) use ($category, $parkingLotID) {
                $attributes = [
                    'category' => $category,
                    'key' => $key,
                    'parking_lot_id' => $parkingLotID,
                ];
                Setting::updateOrCreate($attributes, ['value' => $item]);
            });
        } else {
            ApiResponse::return('类型必填', '', ApiResponse::CODE_INVALID_ARGUMENT);
        }

        $this->logContent = '修改系统配置['.$title.']';
        $this->admin = $admin;

        if (Setting::CATEGORY_SITE === $category) {
            \Cache::delete('site_settings');
        }

        return ApiResponse::return();
    }

    public function wechatTemplates(Request $request): array
    {
        $data = $request->post();

        $settings = Setting::where('category', Setting::CATEGORY_WECHAT_TEMPLATE)->get();
        $keys = $settings->pluck('key')->toArray();

        $templates = array_keys(Setting::KET_WECHAT_TEMPLATES);
        $newTemp = array_diff($templates, $keys);

        if (count($newTemp)) {
            $insertDat = [];
            foreach ($newTemp as $temp) {
                $insertDat[] = [
                    'id' => \Str::orderedUuid()->toString(),
                    'category' => Setting::CATEGORY_WECHAT_TEMPLATE,
                    'key' => $temp,
                    'value' => 0,
                ];
            }

            Setting::insert($insertDat);

            $settings = Setting::where('category', Setting::CATEGORY_WECHAT_TEMPLATE)->get();
        }

        $list = [];
        foreach ($settings as $setting) {
            if ($temp = \Arr::get(Setting::KET_WECHAT_TEMPLATES, $setting['key'])) {
                $temp['id'] = $setting->id;
                $temp['able'] = boolval($setting->value);
                $temp['template_id'] = strval($setting->data);
                $list[] = $temp;
            }
        }

        return ApiResponse::return('', $list);
    }

    public function storeWechatTemplate(Request $request): array
    {
        $data = $request->post();

        $id = \Arr::get($data, 'id');

        if (!$setting = Setting::find($id)) {
            throw new \InvalidArgumentException('未查询到模板消息信息');
        }

        $able = boolval(\Arr::get($data, 'able'));
        $templateId = \Arr::get($data, 'template_id') ?: '';

        $setting->update([
            'data' => $templateId,
            'value' => $able,
        ]);

        return ApiResponse::return();
    }

    public function getVziConfig(Request $request)
    {
        return ApiResponse::success(config('services.vzicloud'));
    }

    public function getH5Url(Request $request)
    {
        $data = $request->post();

        $type = \Arr::get($data, 'type');
        $query = \Arr::get($data, 'query');

        $parkingLotID = getParkingLotID();

        if (!$h5 = config('app.h5_url')) {
            return ApiResponse::fail('未配置h5域名');
        }

        if (!$parkingLot = ParkingLot::find($parkingLotID)) {
            ApiResponse::return('未查询到车场信息', '', ApiResponse::CODE_INVALID_ARGUMENT);
        }

        $path = '';
        switch ($type) {
            case 'park_export': // 车场预付码
                    $path = '/park/order?parking_lot_id=' . $parkingLotID . '&parking_lot_name=' . $parkingLot->name;
                break;
            case 'area_export': // 区域预付码
                    if (!$id = $query) {
                        throw new \InvalidArgumentException('区域ID不可为空');
                    }
                    if (!$area = ParkingLotArea::where('parking_lot_id', $parkingLotID)->where('id', $id)->first()) {
                        throw new \InvalidArgumentException('未查询到区域信息');
                    }
                    if (ParkingLotArea::CATEGORY_OUT !== $area->category) {
                        throw new \InvalidArgumentException('非外场区域');
                    }
                    $path = '/park/order?parking_lot_id=' . $parkingLotID . '&area_id=' . $area->id . '&parking_lot_name=' . $parkingLot->name;
                break;
            case 'lane_export': // 车道出口码
                    if (!$id = $query) {
                        throw new \InvalidArgumentException('车道ID不可为空');
                    }
                    if (!$lane = Lane::where('parking_lot_id', $parkingLotID)->where('id', $id)->first()) {
                        throw new \InvalidArgumentException('未查询到车道信息');
                    }
                        $path = '/park/order?parking_lot_id='.$parkingLotID.'&lane_id='.$lane->id . '&parking_lot_name=' . $parkingLot->name;
                break;
            case 'lane_entrance': // 车道入口码
            default:
                throw new \InvalidArgumentException('类型未开启');
        }

        return ApiResponse::success($h5 . $path);
    }
}
